package com.xja.dubbo.controller;

import com.xja.dubbo.entity.Easybuy_product;
import com.xja.dubbo.entity.Easybuy_product_category;
import com.xja.dubbo.service.ProductCategoryService;
import com.xja.dubbo.service.ProductService;
import com.xja.dubbo.util.PageResult;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author ycz
 * @create 2021-12-15-10:50
 */
@Controller
@RequestMapping("product")
public class ProductController {

    private Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Reference(url = "dubbo://localhost:20881")
    private ProductService productService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductCategoryService productCategoryService;


    @RequestMapping("/findCategory")
    @ResponseBody
    public PageResult findCategory(Integer pid) {
        try {
            logger.info("查询");
            List<Easybuy_product_category> categoryList = productCategoryService.findCategoryByPid(pid);
            return PageResult.getPageResult(200, "true", "查询成功", categoryList) ;

        } catch (Exception e) {
            logger.error("查询错误", e);
        }
        return PageResult.getPageResult(404, "false", "查询异常", null);

    }

    /**
     * 富文本编辑器文件上传
     * request,response
     *
     * @throws Exception
     */
    @RequestMapping("/kindEditorUpLoadFile")
    @ResponseBody
    public Map<String, Object> kindEditorUpLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> resuMap = new HashMap<>();
        logger.info("富文本编辑器的上传图片");
        try {
            // 文件保存目录路径
            String savePath = "E:/idea workspace/production/easy_buy/easy_buy_web/src/main/resources/static/image/";
            String saveUrl = request.getContextPath() + "/image/";
            // 定义允许上传的文件扩展名
            HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("image", "gif,jpg,jpeg,png,bmp");
            // 最大文件大小
            long maxSize = 1000000;
            response.setContentType("text/html; charset=UTF-8");

            File uploadDir = new File(savePath);
            // 判断文件夹是否存在,如果不存在则创建文件夹
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            String dirName = request.getParameter("dir");
            if (dirName == null) {
                dirName = "image";
            }
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = mRequest.getFileMap();
            String fileName = null;
            for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile mFile = entry.getValue();
                fileName = mFile.getOriginalFilename();
                // 检查文件大小
                if (mFile.getSize() > maxSize) {
                    resuMap.put("error", 1);
                    resuMap.put("message", "上传文件大小超过限制。");
                    return resuMap;
                }
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    resuMap.put("error", 1);
                    resuMap.put("message", "文件格式不对。");
                    return resuMap;
                }
                UUID uuid = UUID.randomUUID();
                savePath = savePath + uuid.toString() + "." + fileExt;

                saveUrl += uuid.toString() + "." + fileExt;
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath));
                FileCopyUtils.copy(mFile.getInputStream(), outputStream);
                String serverPath = "E:/idea workspace/production/easy_buy/easy_buy_web/target/classes/static/image/";
                serverPath = serverPath + uuid.toString() + "." + fileExt;
                FileCopyUtils.copy(new File(savePath), new File(serverPath));
                resuMap.put("error", 0);
                resuMap.put("url", saveUrl);
                logger.error("富文本编辑器的上传图片成功:" + saveUrl);
                return resuMap;
            }
        } catch (Exception ex) {
            logger.error("富文本编辑器的上传图片异常", ex);
        }
        resuMap.put("error", 1);
        resuMap.put("message", "有异常");
        return resuMap;
    }

    /**
     * layui图片上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("layUiUpload")
    @ResponseBody
    public Object layUiUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String path = "E:/idea workspace/production/easy_buy/easy_buy_web/src/main/resources/static/upload/";
        try {
            file.transferTo(new File(path + file.getOriginalFilename()));
            map.put("imgurl", file.getOriginalFilename());
            map.put("msg", "上传成功！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return map;
    }


    @RequestMapping("addSave")
    public String addSave(Easybuy_product easybuy_product, @RequestParam("imgs") List<String> productImagesList) {
        try {
            productService.addProduct(easybuy_product, productImagesList);
            return "redirect:/addProduct.html";
        } catch (Exception e) {
            logger.error("添加异常", e);
        }

        return "redirect:/error.html";
    }
}
